package com.ly.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ly.common.core.domain.model.LoginUser;
import com.ly.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill (MetaObject metaObject) {
        log.info ( "start insert fill ...." );
        String username = null;
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser ();
            if ( Objects.nonNull ( loginUser ) ) {
                username = loginUser.getUsername ();
            }
        } catch ( Exception e ) {
        }
        Date date = new Date ();
        this.strictInsertFill ( metaObject, "create_by", String.class, username );
        this.strictInsertFill ( metaObject, "update_by", String.class, username );
        this.strictInsertFill ( metaObject, "createTime", Date.class, date ); // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill ( metaObject, "updateTime", Date.class, date );
    }

    @Override
    public void updateFill (MetaObject metaObject) {
        log.info ( "start update fill ...." );
        String username = null;
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser ();
            if ( Objects.nonNull ( loginUser ) ) {
                username = loginUser.getUsername ();
            }
        } catch ( Exception e ) {
        }
        Date date = new Date ();
        this.strictInsertFill ( metaObject, "update_by", String.class, username );
        this.strictUpdateFill ( metaObject, "updateTime", Date.class, date ); // 起始版本 3.3.0(推荐)
    }
}
